package com.zh.sharding.sale.support.id;

import com.zh.sharding.sale.support.SpringContextHolder;
import org.apache.shardingsphere.sharding.spi.KeyGenerateAlgorithm;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Properties;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author zhou
 * @date 2023/8/24
 */
public class AutoIncIdKeyGenerateAlgorithm implements KeyGenerateAlgorithm {
    private StringRedisTemplate redisTemplate;
    static final String REDIS_KEY_AUTO_ID = "auto_id_table";
    static final String KEY_PREFIX_KEY = "key-prefix";

    private String tableName;
    @Override
    public void init(Properties props) {
        System.out.println(">>> [debug]\t props = "+props);

        this.tableName = getKeyPrefix(props);

        this.redisTemplate = SpringContextHolder.getBean(StringRedisTemplate.class);
        this.redisTemplate.opsForHash().putIfAbsent(REDIS_KEY_AUTO_ID, tableName,"0");
    }

    private String getKeyPrefix(Properties props){
        if (!props.containsKey(KEY_PREFIX_KEY)){
            throw new IllegalArgumentException("table key prefix 没有指定");
        }
        return props.getProperty("key-prefix", "global");
    }

    @Override
    public Comparable<?> generateKey() {
        return redisTemplate.opsForHash().increment(REDIS_KEY_AUTO_ID, tableName, 1);
    }

    @Override
    public String getType() {
        return "AUTO_INC";
    }
}
